package com.tg.base.concurrent.synch;

import com.tg.base.concurrent.SlowAction;
import com.tg.base.concurrent.ThreadSleep;

import java.util.Map;
import java.util.concurrent.*;

public class SynchronizedShareObject {

    private static final ConcurrentHashMap<String, Entity> MAP_A = new ConcurrentHashMap<String, Entity>();
    private static final ConcurrentHashMap<String, Entity> MAP_B = new ConcurrentHashMap<String, Entity>();

    private static final ExecutorService executor = Executors.newFixedThreadPool(2);

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        Entity entity = new Entity();
        entity.setName("tg");

        MAP_A.put("a1", entity);
        MAP_B.put("b1", entity);

        executor.submit(invokeRequest(MAP_A, "a"));
        executor.submit(invokeRequest(MAP_B, "b"));

        ThreadSleep.invoke(TimeUnit.SECONDS, 20);
    }

    private static Runnable invokeRequest(ConcurrentHashMap<String, Entity> map, String prefix) {
        return () -> {
            synchronized (map) {
                System.out.println(Thread.currentThread().getName() + ":working");
                ThreadSleep.invoke(TimeUnit.SECONDS, 2);

                String key = prefix.concat("1");
                Entity entity = map.get(key);
                entity.setName(prefix + ":mark");
                map.put(key, entity);
                System.out.println(Thread.currentThread().getName() + ":done:" + entity.getName());

                System.out.println(Thread.currentThread().getName() + ":thread a:" + MAP_A.get("a1").getName());
            }
        };
    }
}
